package pe.lucene.web.myrating;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class HibernateUtil {
	
	private static final SessionFactory sessionfactory;
	
	static {
		try {
			sessionfactory = new Configuration().configure().buildSessionFactory();
		} catch(Throwable ex) {
			throw new ExceptionInInitializerError(ex);
		}
	}
	
	public static final ThreadLocal local = new ThreadLocal();
	
	public static Session currentSession() throws HibernateException {
		Session s = (Session) local.get();
		
		if (s == null) {
			s = sessionfactory.openSession();
			local.set(s);
		}
		
		return s;
	}
	
	public static void closeSession() throws HibernateException {
		Session s = (Session) local.get();
		local.set(null);
		
		if (s != null) {
			s.close();
		}
	}

}
